#include <stdio.h>
#include <string.h>
#include "ini.h"

typedef struct
{
    const char *id;
    const char *type;
    const char *interface_name;
    const char *wake_on_lan;
    const char *ipv4_method;
    const char *ipv4_dns;
    const char *ipv6_method;
} configuration;

static int handler(void *user, const char *section, const char *name, const char *value)
{
    configuration *pconfig = (configuration *)user;

#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
    if (MATCH("connection", "id")) {
        pconfig->id = strdup(value);
    } else if (MATCH("connection", "type")) {
        pconfig->type = strdup(value);
    } else if (MATCH("connection", "interface-name")) {
        pconfig->interface_name = strdup(value);
    } else if (MATCH("ethernet", "wake-on-lan")) {
        pconfig->wake_on_lan = strdup(value);
    } else if (MATCH("ipv4", "method")) {
        pconfig->ipv4_method = strdup(value);
    } else if (MATCH("ipv4", "dns")) {
        pconfig->ipv4_dns = strdup(value);
    } else if (MATCH("ipv6", "method")) {
        pconfig->ipv6_method = strdup(value);
    } else {
        return 0;  /* unknown section/name, error */
    }
    return 1;
}

int main()
{
    configuration config;

    if (ini_parse("./netplan-eth1.nmconnection", handler, &config) < 0) {
        printf("Can't load the ini file\n");
        return 1;
    }
    printf("Config loaded from %s: id=%s, type=%s, interface-name=%s, wake-on-lan=%s, ipv4_method=%s, ipv4_dns=%s, ipv6_method=%s\n",
            "./netplan-eth1.nmconnection",
            config.id, config.type, config.interface_name, config.wake_on_lan, config.ipv4_method, config.ipv4_dns, config.ipv6_method);


    //写入文件
    FILE *file = fopen("/tmp/eth1.nmconnection", "w");
    if (file == NULL) { printf("Error opening file!\n"); return 1; }

    fprintf(file, "[connection]\n");
    fprintf(file, "id=%s\n", config.id);
    fprintf(file, "type=%s\n", config.type);
    fprintf(file, "interface-name=%s\n", config.interface_name);
    fprintf(file, "\n");
    fprintf(file, "[ethernet]\n");
    fprintf(file, "wake-on-lan=%s\n", config.wake_on_lan);
    fprintf(file, "\n");
    fprintf(file, "[ipv4]\n");
    fprintf(file, "method=%s\n", config.ipv4_method);
    fprintf(file, "dns=%s\n", config.ipv4_dns);
    fprintf(file, "\n");
    fprintf(file, "[ipv6]\n");
    fprintf(file, "method=%s\n", config.ipv6_method);

    fclose(file);

    return 0;
}
